<?php
namespace Admin\Controller;
use Think\Controller;

class LoginController extends Controller {

	public function login() {
		if(IS_POST) {
			// 尝试管理员登陆
			$administrator = D('Administrator');
			$map['username'] = I('post.user');
			$map['password'] = md5(I('post.password'));
			$result = $administrator->where($map)->find();
			if($result) {
				session('uid', $result['id']);
				if($administrator->isSupervisor(I('session.uid'))) {
					session('role', C('ROLE_SUPERVISOR'));
				} else {
					session('role', C('ROLE_ADMINISTRATOR'));
				}
				$this->redirect('Index/index');
			}

			// 尝试教师登陆
			$map = array();
			$result = array();
			$teacher = M('Teacher');
			$map['id'] = (int)I('post.user');
			$map['password'] = md5(I('post.password'));
			$result = $teacher->where($map)->find();
			if($result) {
				session('uid', $result['id']);
				session('role', C('ROLE_TEACHER'));
				$this->redirect('Index/index');
			}

			// 尝试学生登陆
			$map = array();
			$result = array();
			$student = M('Student');
			$map['id'] = I('post.user');
			$map['password'] = md5(I('post.password'));
			$result = $student->where($map)->find();
			if($result) {
				session('uid', $result['id']);
				session('role', C('ROLE_STUDENT'));
				$this->redirect('Index/index');				
			}

			$this->error('账户或密码错误！');
		}
		$this->display();
	}

	public function logout() {
		session(null);
		$this->display('login');
	}

}
